package com.maikang.exammall.repository;

import com.maikang.exammall.entity.Cart;
import com.maikang.exammall.entity.dto.CartDetailDTO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface CartRepository extends BaseRepository<Cart, Long>, JpaSpecificationExecutor<Cart> {

    @Query("SELECT new com.maikang.exammall.entity.dto.CartDetailDTO(" +
            "cart.id, " +
            "cart.refererId, " +
            "cart.userId, " +
            "cart.pkgId, " +
            "cart.pkgCount, " +
            "pkg.priceReal," +
            "pkg.priceOriginal," +
            "pkg.target, " +
            "pkg.avatarUrl, " +
            "hospital.avatarUrl, " +
            "pkg.name, " +
            "hospital.id, " +
            "hospital.name, " +
            "hospital.openDates, " +
            "cart.lastModifiedDate ) FROM Cart cart " +
            "INNER JOIN Package pkg ON cart.pkgId = pkg.id AND pkg.isDeleted = 0 " +
            "INNER JOIN Hospital hospital ON pkg.hospital.id = hospital.id AND hospital.isDeleted = 0 " +
            "WHERE cart.userId = :userId ")
    Slice<CartDetailDTO> findByUserId(@Param("userId") Long userId, Pageable pageable);

    Cart findByUserIdAndPkgIdAndId(Long userId, Long pkgId, Long id);

    @Query("UPDATE Cart cart SET cart.isDeleted = 1 WHERE cart.id IN (:ids)")
    @Modifying
    void deleteAllById(@Param("ids") Iterable<Long> ids);


    // query before update is_deleted flag. slow.
    void deleteByIdIn(List<Long> ids);

}
